<?php
// 团队预约API测试脚本
// 用于验证API接口是否正常工作

require_once '../config/database.php';

try {
    $pdo = new PDO(
        'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET,
        DB_USER,
        DB_PASS,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
    );
    
    echo "✅ 数据库连接成功\n";
    
    // 检查表是否存在
    $stmt = $pdo->query("SHOW TABLES LIKE 'team_reservations'");
    if ($stmt->rowCount() > 0) {
        echo "✅ team_reservations 表存在\n";
        
        // 检查表结构
        $stmt = $pdo->query("DESCRIBE team_reservations");
        $columns = $stmt->fetchAll();
        
        echo "\n📋 表结构检查:\n";
        $requiredColumns = [
            'id', 'team_name', 'visitor_identity', 'contact_name', 
            'contact_unit', 'contact_phone', 'visitor_info', 'need_guide',
            'reservation_date', 'reservation_time', 'end_time', 'visitor_count',
            'user_id', 'status', 'admin_notes', 'approved_by', 'approved_at',
            'created_at', 'updated_at'
        ];
        
        $existingColumns = array_column($columns, 'Field');
        $missingColumns = array_diff($requiredColumns, $existingColumns);
        
        if (empty($missingColumns)) {
            echo "✅ 所有必要字段都存在\n";
        } else {
            echo "❌ 缺少以下字段: " . implode(', ', $missingColumns) . "\n";
        }
        
        // 显示现有字段
        echo "\n📝 现有字段列表:\n";
        foreach ($columns as $column) {
            echo "  - {$column['Field']} ({$column['Type']})\n";
        }
        
        // 检查数据
        $stmt = $pdo->query("SELECT COUNT(*) as count FROM team_reservations");
        $count = $stmt->fetch()['count'];
        echo "\n📊 当前数据记录数: {$count}\n";
        
        if ($count > 0) {
            // 显示一条示例数据
            $stmt = $pdo->query("SELECT * FROM team_reservations LIMIT 1");
            $sample = $stmt->fetch();
            echo "\n📄 示例数据:\n";
            foreach ($sample as $key => $value) {
                echo "  {$key}: {$value}\n";
            }
        }
        
    } else {
        echo "❌ team_reservations 表不存在\n";
        echo "请执行以下脚本之一来创建表:\n";
        echo "  - fix_team_reservations.sql (完全重建)\n";
        echo "  - update_team_reservations.sql (增量更新)\n";
    }
    
    // 测试API访问
    echo "\n🔧 API测试建议:\n";
    echo "1. 确保表结构完整\n";
    echo "2. 访问 /api/team_reservations.php?action=list 测试列表接口\n";
    echo "3. 检查管理后台是否能正常加载团队预约页面\n";
    
} catch (PDOException $e) {
    echo "❌ 数据库连接失败: " . $e->getMessage() . "\n";
} catch (Exception $e) {
    echo "❌ 错误: " . $e->getMessage() . "\n";
}

echo "\n" . str_repeat("=", 50) . "\n";
echo "团队预约系统检查完成\n";
echo "时间: " . date('Y-m-d H:i:s') . "\n";
echo str_repeat("=", 50) . "\n";
?>